Coroutines in Lua
Lua coroutines are cooperative execution contexts, not operating-system threads. They run until they return, raise an error, or explicitly yield.
local producer = coroutine.create(function()
for i = 1, 3 do
coroutine.yield(i * i)
end
return "finished"
end)
while true do
local ok, value = coroutine.resume(producer)
if not ok then
error(value)
end
print(value)
if coroutine.status(producer) == "dead" then
break
end
end
Coroutines alone do not make blocking I/O asynchronous. An event loop or nonblocking I/O library is required.
If an abandoned coroutine owns to-be-closed variables, call coroutine.close so their cleanup handlers run.